# -*- coding: utf-8 -*-
# PTK archive copying v.4.5

import os
import shutil
import datetime
import time
import re
import win32api
from datetime import date, datetime, timedelta
from collections import deque

log_file = "log.txt"

def logfile(message_log, message_cmd):
    current_time = datetime.now()
    formatted_time = current_time.strftime("%d.%m.%y %H:%M:%S.%f")[:-3]
    print("{} - {}".format(formatted_time, str(message_cmd)))
    with open(log_file, 'a') as file:
        file.write("{} - {}\n".format(formatted_time, str(message_log)))

def runtime(times, i1=False):
    end_time = time.time()
    elapsed_time = (end_time - times) / 60
    if i1:
        logfile("Время копирования {:.0f} мин.".format(elapsed_time), "Runtime {:.0f} min.".format(elapsed_time))
    else:
        logfile("Общее время копирования {:.0f} мин.".format(elapsed_time), "Runtime {:.0f} min.".format(elapsed_time))
        

def is_path_available(path):
    for i in range(5):
        if os.path.exists(path):
            return True
        else:
            time.sleep(300)
    return False


def copy_files(source_path, dest_path, queue, iter):
    if not is_path_available(source_path):
        logfile("Исходная папка недоступна", "Source path not available")
        return False
    if not is_path_available(dest_path):
        logfile("Папка назначения недоступна", "Destination path not available")
        return False
    files_to_copy = [file_name for file_name in os.listdir(source_path)
                     if os.path.isfile(os.path.join(source_path, file_name))]
    s_time = time.time()
    files_c = 0
    for file_name in files_to_copy:
        file_path = os.path.join(source_path, file_name)
        try:
            file_date = datetime.fromtimestamp(os.path.getmtime(file_path))
#            now = datetime.now()                                                            #
#            start_of_hour = now.replace(minute=0, second=0, microsecond=0)                  #
#            previous_hour = start_of_hour - timedelta(minutes=15)                           #
#            if previous_hour <= file_date.replace(microsecond=0) < start_of_hour:           #
            if file_date.date() == date.today() - timedelta(days=1): # прошлые сутки       ##
                if not file_name.startswith("00000000"):
                    queue.append(file_path)
                    files_c += 1
        except WindowsError as e:
            logfile("Ошибка при получении даты файла {}: {}".format(file_path, e), "Error getting file date for {}: {}".format(file_path, e))
            continue  # продолжаем копирование остальных файлов

    logfile("Копирование {} файлов, из {} в {}".format(files_c, source_path, dest_path), "Copy {} files, from {} to {}".format(files_c, source_path, dest_path))
    files_to_copy_length = len(files_to_copy)  # Сохраняем длину списка в отдельную переменную
    files_copied = 0
    for _ in range(files_to_copy_length):
        if queue:
            file_path = queue.popleft()
            shutil.copy2(file_path, dest_path)
            files_copied += 1
    logfile("Копирование успешно завершено.", "Copying completed successfully")
    runtime(s_time, True)
    return True

def get_current_date():
    return date.today()

def get_previous_date(current_date):
    if current_date.day == 1:
        return current_date.replace(day=1) - timedelta(days=1)
    else:
        return current_date	

def get_folder_name(date):
    return date.strftime("%Y.%m")

def run():
    start_time = time.time()
    current_date = get_current_date()
    previous_date = get_previous_date(current_date)
    source_paths = ["\\\\192.168.1.100\\Archive", "\\\\192.168.1.101\\Archive", "\\\\192.168.1.102\\Archive"]
    dest_paths = ["\\\\192.168.1.200\\Archive1\\", "\\\\192.168.1.200\\Archive2\\", "\\\\192.168.1.200\\Archive3\\"]
    folder_names = [get_folder_name(previous_date), get_folder_name(previous_date), get_folder_name(previous_date)]
    iter = 0
	
    for source_path, dest_path, folder_name in zip(source_paths, dest_paths, folder_names):
        dest_path += folder_name
        queue = deque()
        iter += 1
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)
        if not copy_files(source_path, dest_path, queue, iter):
            logfile("Ошибка копироваиня файлов из {} в {}".format(source_path, dest_path), "Error copying files from {} to {}".format(source_path, dest_path))
            return

    logfile("Копирование файлов завершено успешно.", "Files copied successfully")
    runtime(start_time)
    print("\nCopying completed.\n----------------------------------------------------------------------\n")
    with open(log_file, 'a') as file:
        file.write("\nКопирование завершено.\n----------------------------------------------------------------------\n")

if __name__ == "__main__":
    print("\n----------------------------------------------------------------------\nStart copying...\n")
    with open(log_file, 'a') as file:
        file.write("\n----------------------------------------------------------------------\nНачало копирования...\n")
    run()